package com.vilen.retrofit2helloworld_1;

import android.os.Bundle;
import android.util.Log;
import com.vilen.retrofit2helloworld_1.api.ApiRx3;
import com.vilen.retrofit2helloworld_1.domain.ResponseJson3;
import com.vilen.retrofit2helloworld_1.domain.User;
import nucleus.presenter.RxPresenter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action2;
import rx.functions.Func0;
import rx.schedulers.Schedulers;

public class MainRxMvpPresent extends RxPresenter<MainRxMvpActivity> {
  private static final int REQUEST_ITEMS = 1;

  @Override protected void onCreate(Bundle savedState) {
    super.onCreate(savedState);
    restartableLatestCache(REQUEST_ITEMS, new Func0<Observable<ResponseJson3<User>>>() {
      @Override public Observable<ResponseJson3<User>> call() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://36.107.180.200:8080/")
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(JacksonConverterFactory.create())
            .build();
        ApiRx3 apiRx3 = retrofit.create(ApiRx3.class);
        return apiRx3.getUserList()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
      }
    }, new Action2<MainRxMvpActivity, ResponseJson3<User>>() {
      @Override
      public void call(MainRxMvpActivity mainRxMvpActivity, ResponseJson3<User> userResponseJson3) {
        mainRxMvpActivity.onItems(userResponseJson3);
      }
    }, new Action2<MainRxMvpActivity, Throwable>() {
      @Override public void call(MainRxMvpActivity mainRxMvpActivity, Throwable throwable) {
        Log.e("MVP", throwable.getMessage().toString());
      }
    });
  }

  public void request() {
    start(REQUEST_ITEMS);
  }
}
